home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C20 / Thesaurus.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  2.1 KB  |  79 lines

  1. //: C20:Thesaurus.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // A map of vectors
  7. #include <map>
  8. #include <vector>
  9. #include <string>
  10. #include <iostream>
  11. #include <algorithm>
  12. #include <ctime>
  13. using namespace std;
  14.  
  15. typedef map<string, vector<string> > Thesaurus;
  16. typedef pair<string, vector<string> > TEntry;
  17. typedef Thesaurus::iterator TIter;
  18.  
  19. ostream& operator<<(ostream& os,const TEntry& t){
  20.   os << t.first << ": ";
  21.   copy(t.second.begin(), t.second.end(),
  22.     ostream_iterator<string>(os, " "));
  23.   return os;
  24. }
  25.  
  26. // A generator for thesaurus test entries:
  27. class ThesaurusGen {
  28.   static const string letters;
  29.   static int count;
  30. public:
  31.   int maxSize() { return letters.size(); }
  32.   ThesaurusGen() { srand(time(0)); }
  33.   TEntry operator()() {
  34.     TEntry result;
  35.     if(count >= maxSize()) count = 0;
  36.     result.first = letters[count++];
  37.     int entries = (rand() % 5) + 2;
  38.     for(int i = 0; i < entries; i++) {
  39.       int choice = rand() % maxSize();
  40.       char cbuf[2] = { 0 };
  41.       cbuf[0] = letters[choice];
  42.       result.second.push_back(cbuf);
  43.     }
  44.     return result;
  45.   }
  46. };
  47.  
  48. int ThesaurusGen::count = 0;
  49. const string ThesaurusGen::letters("ABCDEFGHIJKL"
  50.   "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  51.  
  52. int main() {
  53.   Thesaurus thesaurus;
  54.   // Fill with 10 entries:
  55.   generate_n(
  56.     inserter(thesaurus, thesaurus.begin()), 
  57.     10, ThesaurusGen());
  58.   // Print everything:
  59.   copy(thesaurus.begin(), thesaurus.end(),
  60.     ostream_iterator<TEntry>(cout, "\n"));
  61.   // Ask for a "word" to look up:
  62.   while(true) {
  63.     cout << "Select a \"word\", 0 to quit: ";
  64.     for(TIter it = thesaurus.begin(); 
  65.       it != thesaurus.end(); it++)
  66.       cout << (*it).first << ' ';
  67.     cout << endl;
  68.     string reply;
  69.     cin >> reply;
  70.     if(reply.at(0) == '0') return 0; // Quit
  71.     if(thesaurus.find(reply) == thesaurus.end())
  72.       continue; // Not in list, try again
  73.     vector<string>& v = thesaurus[reply];
  74.     copy(v.begin(), v.end(), 
  75.       ostream_iterator<string>(cout, " "));
  76.     cout << endl;
  77.   }
  78. } ///:~
  79.